package com.lu.manage.core.schedue.quartz.schedule;

import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class QuartzManage {

    private static Logger logger = LoggerFactory.getLogger(QuartzManage.class);

    @Autowired
    private Scheduler scheduler;

    /**
     * 添加任务
     */
    public void addJob(ScheduleJob job) throws Exception {
        //实例任务执行类
        Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(job.getClassBean()).newInstance().getClass();
        //创建jobDetail实例，绑定Job实现类，指定Job名称，所在组，并且绑定Job
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getJobName(),job.getJobGroup()).build();
        //定义调度触发规则
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(),job.getJobGroup())
                .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                .withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression())).startNow().build();
        //把作业和触发器注册到任务调度中心
        scheduler.scheduleJob(jobDetail,trigger);
        if(!scheduler.isShutdown()){
            scheduler.start();
        }
    }

    /**
     * 删除一个Job
     */
    public void deletejob(ScheduleJob job) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(job.getJobName(),job.getJobGroup());
        scheduler.deleteJob(jobKey);
    }

    /**
     * 立即执行一个已在注册中心的Job
     */
    public void runJobNow(ScheduleJob job) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(job.getJobName(),job.getJobGroup());
        scheduler.triggerJob(jobKey);
    }

    /**
     * 立即执行job
     * 如果job不在任务中心中则临时创建一个任务执行，执行完毕后自动销毁
     */
    public void addTempJobNow(ScheduleJob job) throws Exception {
        Class<? extends Job> className = (Class<? extends Job>) Class.forName(job.getClassBean()).newInstance().getClass();
        JobDetail jobDetail = JobBuilder.newJob(className).withIdentity(job.getJobName(),job.getJobGroup()).build();
        SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(),job.getJobGroup())
                .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(3)
                        .withRepeatCount(0)).build();
        scheduler.scheduleJob(jobDetail,simpleTrigger);
    }

    /**
     * 更新cron表达式
     * @param job
     */
    public void updateJobCron(ScheduleJob job) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(),job.getJobGroup());
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
        cronTrigger = cronTrigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
        scheduler.rescheduleJob(triggerKey,cronTrigger);
    }

    /**
     * 获取所有计划中的任务列表
     * @return
     */
    public List<ScheduleJob> getAllJob(){
        List<ScheduleJob> jobList = null;
        try {
            GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
            Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
            jobList = new ArrayList<>();
            for(JobKey jobKey : jobKeys){
                List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                for(Trigger trigger : triggers){
                    ScheduleJob job = new ScheduleJob();
                    job.setJobName(jobKey.getName());
                    job.setJobGroup(jobKey.getGroup());
                    job.setDescrip("触发器：" + trigger.getKey());
                    Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                    job.setJobState(triggerState.name());
                    if(trigger instanceof CronTrigger){
                        CronTrigger cronTrigger = (CronTrigger) trigger;
                        job.setCronExpression(cronTrigger.getCronExpression());
                    }
                    jobList.add(job);
                }
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return jobList;
    }

    /**
     * 获取所有正在运行的job
     * @return
     */
    public List<ScheduleJob> getRunningJob(){
        List<JobExecutionContext> executionContexts = null;
        List<ScheduleJob> jobList = null;
        try {
            executionContexts = scheduler.getCurrentlyExecutingJobs();
            jobList = new ArrayList<>(executionContexts.size());
            for(JobExecutionContext executionContext : executionContexts){
                ScheduleJob job = new ScheduleJob();
                JobDetail jobDetail = executionContext.getJobDetail();
                JobKey jobKey = jobDetail.getKey();
                Trigger trigger = executionContext.getTrigger();
                job.setJobName(jobKey.getName());
                job.setJobGroup(jobKey.getGroup());
                job.setDescrip("触发器：" + trigger.getKey());
                Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                job.setJobState(triggerState.name());
                if(trigger instanceof CronTrigger){
                    CronTrigger cronTrigger = (CronTrigger) trigger;
                    job.setCronExpression(cronTrigger.getCronExpression());
                }
                jobList.add(job);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return jobList;
    }

}
